//
//  CLLoginModel.m
//  chanlin
//
//  Created by Ryan on 14-12-1.
//  Copyright (c) 2014年 chanlin. All rights reserved.
//

#import "CLLoginModel.h"
#import "UMSocial.h"
#import "ChangyanSDK.h"

@implementation CLLoginModel

SGR_DEF_SINGLETION(CLLoginModel)


- (void)loginWithOpenId:(NSString *)openID site:(NSString *)site nickname:(NSString *)nickName avatar:(NSString *)avatar
uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    NSString *url=[[CLGloble sharedInstance].urls sgrGetStringForKey:@"login"];
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    [params sgrSetObject:openID forKey:@"openid"];
    [params sgrSetObject:site forKey:@"site"];
    [params sgrSetObject:nickName forKey:@"nickname"];
    [params sgrSetObject:avatar forKey:@"avatar"];
    NSString *md5str=[[CLGloble sharedInstance] md5:site];
    md5str=[[CLGloble sharedInstance] md5:[NSString stringWithFormat:@"%@%@",md5str,openID]];
    md5str=[[CLGloble sharedInstance] md5:[NSString stringWithFormat:@"%@chanlin",md5str]];
    
    
    [params sgrSetObject:md5str forKey:@"md"];
    
    [self postWithUrl:url param:params
            dataBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
                if(success && _isStrNotNull([responseObj sgrFGetStringForKey:@"token"])){
                    CLUser *user=[CLUser new];
                    user.openId=openID;
                    user.site=site;
                    user.token=[responseObj sgrFGetStringForKey:@"token"];
                    user.uid=[responseObj sgrFGetStringForKey:@"userid"];
                    user.status=[[responseObj sgrGetNumberForKey:@"status"] intValue];
                    user.nickName=[responseObj sgrGetStringForKey:@"nickname"];
                    user.imgUrl=[responseObj sgrGetStringForKey:@"userpic"];
                    user.groupId=[responseObj sgrFGetStringForKey:@"groupid"];
                    [CLGloble sharedInstance].user=user;
                    
                    [ChangyanSDK loginSSO:user.uid
                                 userName:user.nickName
                               profileUrl:[NSString stringWithFormat:@"groupId=%@",_safeStr(user.groupId)]
                                   imgUrl:user.imgUrl
                            completeBlock:^(CYStatusCode statusCode, NSString *responseStr) {
                                if(statusCode!=CYSuccess){
                                    [[CLGloble sharedInstance] showTieSuccessMessage:@"同步评论登陆失败"
                                                                          subMessage:@"建议注销重新登陆尝试"];
                                }
                            }];
                }
            } uiBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
                
                sgrSafeMainThread(^{
                    block(success && _isStrNotNull([responseObj sgrFGetStringForKey:@"token"]),responseObj,nil);
                });
            }];
    
    
}


- (void)reLogin{
    if(_isStrNULL([CLGloble sharedInstance].user.token)) return;
    
    if(_isStrNotNull([CLGloble sharedInstance].user.openId)){
    
    NSString *url=[[CLGloble sharedInstance].urls sgrGetStringForKey:@"login"];
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    NSString *openID=[CLGloble sharedInstance].user.openId;
    NSString *site=[CLGloble sharedInstance].user.site;
    
    [params sgrSetObject:openID forKey:@"openid"];
    [params sgrSetObject:site forKey:@"site"];
    [params sgrSetObject:[CLGloble sharedInstance].user.nickName forKey:@"nickname"];
    [params sgrSetObject:[CLGloble sharedInstance].user.imgUrl forKey:@"avatar"];
    NSString *md5str=[[CLGloble sharedInstance] md5:site];
    md5str=[[CLGloble sharedInstance] md5:[NSString stringWithFormat:@"%@%@",md5str,openID]];
    md5str=[[CLGloble sharedInstance] md5:[NSString stringWithFormat:@"%@chanlin",md5str]];
    
    
    [params sgrSetObject:md5str forKey:@"md"];
    [self postWithUrl:url param:params
            dataBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
                if(success){
                    CLUser *user=[CLUser new];
                    user.openId=openID;
                    user.site=site;
                    user.token=[responseObj sgrFGetStringForKey:@"token"];
                    user.uid=[responseObj sgrFGetStringForKey:@"userid"];
                    user.status=[[responseObj sgrGetNumberForKey:@"status"] intValue];
                    user.nickName=[responseObj sgrGetStringForKey:@"nickname"];
                    user.imgUrl=[responseObj sgrGetStringForKey:@"userpic"];
                    user.groupId=[responseObj sgrFGetStringForKey:@"groupid"];
                    [CLGloble sharedInstance].user=user;
                    
                    [ChangyanSDK loginSSO:user.uid
                                 userName:user.nickName
                               profileUrl:[NSString stringWithFormat:@"groupId=%@",_safeStr(user.groupId)]
                                   imgUrl:user.imgUrl
                            completeBlock:^(CYStatusCode statusCode, NSString *responseStr) {
                                if(statusCode!=CYSuccess){
                                    [[CLGloble sharedInstance] showTieSuccessMessage:@"同步评论登陆失败"
                                                                          subMessage:@"建议注销重新登陆尝试"];
                                }
                            }];
                }
            } uiBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
                
                           }];
    }else{
        [self loginIn:[CLGloble sharedInstance].user.email password:[CLGloble sharedInstance].user.password uiBlock:^(BOOL success, id responseObj, NSString *message) {
            
        }];
    }
}


//- (void)loginIn:(NSString *)usrName password:(NSString *)password uiBlock:(void (^)(BOOL, id, NSString *))block{
//    
//}


- (void)loginWeichat:(UIViewController *)controller uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession];
    __weak typeof(self) me=self;
    snsPlatform.loginClickHandler(controller,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        if (response.responseCode == UMSResponseCodeSuccess  ) {
            
            
            
            [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToWechatSession  completion:^(UMSocialResponseEntity *response){
                if (response.responseCode == UMSResponseCodeSuccess  && [response.data isKindOfClass:[NSDictionary class]]) {
                  
                    
                    [me loginWithOpenId:[response.data sgrFGetStringForKey:@"openid"]
                                   site:@"wechat"
                               nickname:[response.data sgrGetStringForKey:@"screen_name"]
                                 avatar:[response.data sgrGetStringForKey:@"profile_image_url"] uiBlock:block];

                }else{
                     block(NO,nil,@"登陆失败");
                }
            }];
            
            
        }else{
           block(NO,nil,@"登陆失败");
        }
        
    });
}

- (void)loginSina:(UIViewController *)controller uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    __weak typeof(self) me=self;
    snsPlatform.loginClickHandler(controller,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToSina
                                                             completion:^(UMSocialResponseEntity *response) {
                                                                 if(response.responseCode==UMSResponseCodeSuccess && [response.data isKindOfClass:[NSDictionary class]]){
                                                                  
                                                                     [me loginWithOpenId:[response.data sgrFGetStringForKey:@"uid"]
                                                                                    site:@"sina"
                                                                                nickname:[response.data sgrGetStringForKey:@"screen_name"]
                                                                                  avatar:[response.data sgrGetStringForKey:@"profile_image_url"] uiBlock:block];
                                                                 }else{
                                                                     block(NO,nil,@"登陆失败");
                                                                 }
                                                             }];
        

    });
}

- (void)loginQQ:(UIViewController *)controller uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQzone];
    __weak typeof(self) me=self;
    snsPlatform.loginClickHandler(controller,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToQzone
                                                             completion:^(UMSocialResponseEntity *response) {
                                                                 
                                                                 if(response.responseCode==UMSResponseCodeSuccess && [response.data isKindOfClass:[NSDictionary class]]){
                                                                   
                                                                     [me loginWithOpenId:[response.data sgrFGetStringForKey:@"uid"]
                                                                                    site:@"qq"
                                                                                nickname:[response.data sgrGetStringForKey:@"screen_name"]
                                                                                  avatar:[response.data sgrGetStringForKey:@"profile_image_url"] uiBlock:block];
                                                                 }else{
                                                                     block(NO,nil,@"登陆失败");
                                                                 }
                                                             }];
        
    });
}

- (void)loginIn:(NSString *)usrName password:(NSString *)password
uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    if(_isStrNULL(usrName)|| _isStrNULL(password)) return;
    NSString *url=@"http://appv2.chanlin.org/e/opclient/applogin.php";
    NSString *md=[[CLGloble sharedInstance] md5:usrName];
    md=[[CLGloble sharedInstance] md5:[md stringByAppendingString:password]];
    md=[[CLGloble sharedInstance] md5:[md stringByAppendingString:@"chanlin_client_login"]];
    NSDictionary *param=@{@"email":_safeStr(usrName),@"password":_safeStr(password),@"md":_safeStr(md)};
    
    [self postWithUrl:url param:param dataBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
        
        if(success && _isStrNotNull([responseObj sgrFGetStringForKey:@"token"])){
            CLUser *user=[CLUser new];
//            user.openId=openID;
//            user.site=site;
            user.token=[responseObj sgrFGetStringForKey:@"token"];
            user.email=usrName;
            user.password=password;
            user.uid=[responseObj sgrFGetStringForKey:@"userid"];
            user.status=[[responseObj sgrGetNumberForKey:@"status"] intValue];
            user.nickName=[responseObj sgrGetStringForKey:@"nickname"];
            user.imgUrl=[responseObj sgrGetStringForKey:@"userpic"];
            user.groupId=[responseObj sgrFGetStringForKey:@"groupid"];
            [CLGloble sharedInstance].user=user;
            
            [ChangyanSDK loginSSO:user.uid
                         userName:user.nickName
                       profileUrl:[NSString stringWithFormat:@"groupId=%@",_safeStr(user.groupId)]
                           imgUrl:user.imgUrl
                    completeBlock:^(CYStatusCode statusCode, NSString *responseStr) {
                        if(statusCode!=CYSuccess){
                            [[CLGloble sharedInstance] showTieSuccessMessage:@"同步评论登陆失败"
                                                                  subMessage:@"建议注销重新登陆尝试"];
                        }
                    }];

        }
        
    } uiBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {

        if(block){
            block(success && _isStrNotNull([responseObj sgrFGetStringForKey:@"token"]),responseObj,nil);
        }
    }];
    
    
    
}

- (void)editImg:(NSString *)base64Img nickName:(NSString *)nickName uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    if(_isStrNULL([CLGloble sharedInstance].user.token)){
        sgrSafeMainThread(^{
            block(NO,nil,@"请登录");
        })
        return;
    }
    NSString *url=[[CLGloble sharedInstance].urls sgrGetStringForKey:@"userEdit"];
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    if(_isStrNotNull(base64Img)){
        [dic sgrSetObject:base64Img forKey:@"userpic"];
    }
    if(_isStrNotNull(nickName)){
        [dic sgrSetObject:nickName forKey:@"nickname"];
    }
    [dic sgrSetObject:[CLGloble sharedInstance].user.token forKey:@"token"];
    
    [self postWithUrl:url param:dic
           dataBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
               
               
        
    } uiBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
        if(block){
            block(success,responseObj,nil);
        }
    }];
}

@end
